const financeGoal = require('../../../../utils/finance-goal');
Page({
  data: {
    attrList: [], // 支持的属性
    goalList: [], // 已配置目标
    goalText: '', // 当前输入内容
    goalTextList: [], // 追加填充内容
    showAdd: false,
    editIndex: -1, // -1为添加，>=0为编辑
    cursor: 0, // 记录textarea的光标位置
  },
  async onLoad() {
    await this.initData();
  },
  async initData() {
    const res = await financeGoal.goalInit();
    this.setData({
      attrList: res.list || [],
      goalList: res.goals || [],
      goalText: '',
      goalTextList: [],
      showAdd: false,
      editIndex: -1,
      cursor: 0,
    });
  },
  onAttrTap(e) {
    const value = e.currentTarget.dataset.value;
    let { goalText = '', cursor = 0 } = this.data;
    if (typeof cursor !== 'number' || cursor < 0) cursor = goalText.length;
    const insertText = `#{${value}}`;
    const newText = goalText.slice(0, cursor) + insertText + goalText.slice(cursor);
    this.setData({
      goalText: newText,
      cursor: cursor + insertText.length,
      selectionStart: cursor + insertText.length,
      selectionEnd: cursor + insertText.length
    });
  },
  onGoalInput(e) {
    this.setData({ goalText: e.detail.value, cursor: e.detail.cursor });
  },
  onAppendAttr() {
    if (!this.data.goalText.trim()) return;
    this.setData({
      goalTextList: [...this.data.goalTextList, this.data.goalText],
      goalText: ''
    });
  },
  // 长按属性复制
  onAttrCopy(e) {
    const value = e.currentTarget.dataset.value;
    if (!value) return;
    wx.setClipboardData({
      data: `#{${value}}`,
      success: () => {
        wx.showToast({ title: '已复制', icon: 'none' });
      }
    });
  },
  // 清空输入内容
  onClearGoalText() {
    this.setData({ goalText: '', goalTextList: [], editIndex: -1, goalTextList: [] });
  },
  // 提交目标数据
  async onSubmitGoal() {
    const { goalTextList, goalText, editIndex, goalList } = this.data;
    let submitText = goalTextList.join('\n');
    if (goalText.trim()) submitText += (submitText ? '\n' : '') + goalText.trim();
    if (!submitText) return wx.showToast({ title: '请输入目标内容', icon: 'none' });
    wx.showLoading({ title: editIndex >= 0 ? '编辑中...' : '提交中...' });
    try {
      if (editIndex >= 0) {
        await financeGoal.goalSubmit({ id: goalList[editIndex].id, sourceText: submitText });
      } else {
        await financeGoal.goalSubmit({ sourceText: submitText });
      }
      wx.hideLoading();
      await this.initData();
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title: (e && e.data && e.data.msg) || '操作失败', icon: 'none' });
    }
  },
  onEditGoal(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.goalList[idx];
    this.setData({
      showAdd: true,
      goalText: item.sourceText,
      goalTextList: [],
      editIndex: idx
    });
  },
  async onDelGoal(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.goalList[idx];
    wx.showModal({
      title: '删除目标',
      content: '确定要删除该目标吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          try {
            await financeGoal.goalDelete(item.id);
            wx.hideLoading();
            await this.initData();
          } catch (e) {
            wx.hideLoading();
            wx.showToast({ title: (e && e.data && e.data.msg) || '删除失败', icon: 'none' });
          }
        }
      }
    });
  },
}); 